using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class PlayerWeaponManager : MonoBehaviour
{
    public List<WeaponController> startingWeapon = new List<WeaponController>();

    public Camera weaponCamera;
    
    public Transform weaponParentSocket;

    public UnityAction<WeaponController> onSwitchedToweapon;

    private WeaponController[] _weaponStlots = new WeaponController[9];

    private void Start()
    {
        onSwitchedToweapon += OnWeaponSwitched;//初始化

        foreach (WeaponController weapon in startingWeapon)
        {
            AddWeapon(weapon);
        }

        SwitchWeapon();
    }

    private void Update()
    {
        WeaponController activeWeapon = _weaponStlots[0];

        if (activeWeapon)
        {
            activeWeapon.HandleShootInput(FPSContorller.Instance.GetFireInputHeld());
        }
    }

    public bool AddWeapon(WeaponController weaponPrefab)
    {
        for(int i=0;i<_weaponStlots.Length;i++)
        {
            WeaponController weaponInstance = Instantiate(weaponPrefab, weaponParentSocket);
            weaponInstance.transform.localPosition = Vector3.zero;
            weaponInstance.transform.localRotation = Quaternion.identity;

            weaponInstance.owner = gameObject;
            weaponInstance.sourcePrefab = weaponPrefab.gameObject;
            weaponInstance.showWeapon(false);

            _weaponStlots[i] = weaponInstance;
            return true;
        }
        return false;
    }

    public void SwitchWeapon()
    {
        SwitchWeaponToIndex(0);
    }

    public void SwitchWeaponToIndex(int newWeaponIndex)
    {
        if (newWeaponIndex >= 0)
        {
            WeaponController newWeapon = GetWeaponAtSlotIndex(newWeaponIndex);

            if (onSwitchedToweapon != null)
            {
                onSwitchedToweapon.Invoke(newWeapon);
            }
        }
    }

    public WeaponController GetWeaponAtSlotIndex(int index)
    {
        if (index >= 0 && index < _weaponStlots.Length)
        {
            return _weaponStlots[index];
        }

        return null;
    }
    private void OnWeaponSwitched(WeaponController newWeapon)
    {
        if (newWeapon != null)
        {
            newWeapon.showWeapon(true);
        }
    }
}
